// Package cmd @author <chengjiang@buffalo-robot.com>
// @date 2023/1/13
// @note
package cmd

import (
	"bytes"
	"deploy-tools/postfile/common/strings"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"

	"github.com/spf13/cobra"
)

type deployType string

const (
	_           deployType = ""
	fileName               = "fileName"
	repoName               = "repoName"
	projectName            = "projectName"
	branchName             = "branchName"
	tagID                  = "tagID"
	changeLog              = "changeLog"
	remark                 = "remark"
)

// flags:
var (
	cfgFile string
	//
	emptyString = ""
	postObjMap  = map[deployType]string{
		fileName:    emptyString,
		repoName:    emptyString,
		projectName: emptyString,
		branchName:  emptyString,
		tagID:       emptyString,
		changeLog:   emptyString,
		remark:      emptyString,
	}
)

var (
	file    string
	repo    string
	project string
	branch  string
	tagI    string
	changeL string
	remar   string
)

// rootCmd represents the base command when called without any subcommands
var postCmd = &cobra.Command{
	Use:   "post [flags]",
	Short: "post comand, used to post the file to web",
	Long: `post, 
used to post the file to web.
	postfile：
		1. post：发布到后台管理端的部署管理模块.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	Run: func(cmd *cobra.Command, args []string) {
		sbUrl := strings.NewStrBuilder()
		sbUrl.StrAppend(Conf.posturl.base).
			StrAppend(Conf.posturl.suffix)
		println("now, post to the url: ", sbUrl.StrAppend(", method: ").StrAppend(Conf.posturl.method).ToString())
		println("the data: ")
		postObjMap[fileName] = file
		postObjMap[repoName] = repo
		postObjMap[projectName] = project
		postObjMap[branchName] = branch
		postObjMap[tagID] = tagI
		postObjMap[changeLog] = changeL
		postObjMap[remark] = remar
		//
		postJson, _ := json.Marshal(postObjMap)
		fmt.Println(string(postJson))
		// post to url:
		err := postUrl(sbUrl, postJson)
		if err != nil {
			handleError(err)
		}
	},
	//RunE: func(cmd *cobra.Command, args []string) error {
	//	return errors.New("something error by using the post command")
	//},
}

func init() {
	// post url:
	Conf.posturl.base = "http://8.129.20.12/"
	Conf.posturl.suffix = "basis/deployment-file"
	Conf.posturl.method = "post"
	//
	// Here you will define your flags.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.
	//rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.deploy-tools.yaml)")
	postCmd.Flags().StringVarP(&file, "filename", "f", "", "this is for oss file name")
	postCmd.Flags().StringVarP(&repo, "reponame", "r", "", "for repository name")
	postCmd.Flags().StringVarP(&project, "proname", "p", "", "for project name")
	postCmd.Flags().StringVarP(&branch, "branchname", "b", "", "for branch name")
	postCmd.Flags().StringVarP(&tagI, "tagid", "t", "", "tag id")
	postCmd.Flags().StringVarP(&changeL, "changelog", "c", "", "change log")
	postCmd.Flags().StringVarP(&remar, "remark", "m", "", "remark")
	//postCmd.Flags().StringVarP(&Conf.posturl.token, "token", "n", "", "U-Token for auth")
}

func postUrl(sbUrl *strings.StrBuilder, reqJson []byte) error {
	req, err := http.NewRequest(Conf.posturl.method, sbUrl.ToString(), bytes.NewBuffer(reqJson))
	if err != nil {
		handleError(err)
	}
	req.Header.Set("Content-Type", "application/json")
	//
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		handleError(err)
	}
	defer resp.Body.Close()
	//
	println("the response")
	if resp.StatusCode == http.StatusOK {
		println("success: ")
		fmt.Println(resp.Body)
	} else {
		println("failed: ")
		fmt.Println(resp.Body)
		return errors.New(strings.NewStrBuilder("在post请求的时候发生错误，状态码：status：").StrAppend(int64(resp.StatusCode)).ToString())
	}
	return err
}
